package com.mojito.gorm.bind;

import com.mojito.gorm.session.GormSession;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author mojito
 */
public class GormMapperRegistry {
    private final Map<Class<?>, GormMapperProxyFactory> factoryMap = new ConcurrentHashMap<>(64);

    /**
     * 在Configuration中解析接口上的注解时，存入接口和工厂类的映射关系
     *
     * @param clazz
     * @param <T>
     */
    public <T> void addMapper(Class<?> clazz) {
        factoryMap.put(clazz, new GormMapperProxyFactory(clazz));
    }

    /**
     * 创建一个代理对象
     */
    public <T> T getMapper(Class<T> clazz, GormSession sqlSession) {
        GormMapperProxyFactory proxyFactory = factoryMap.get(clazz);
        if (proxyFactory == null) {
            throw new RuntimeException("Type: " + clazz + " can not find");
        }
        return (T) proxyFactory.newInstance(sqlSession);
    }
}
